﻿using ICSharpCode.SharpZipLib.Zip;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Learun.Application.Web.Common
{
    /// <summary>
    /// 项目备份作业
    /// </summary>
    public class ProjectBakupJob
    {
        /// <summary>
        /// 备份执行
        /// </summary>
        /// <returns></returns>
        public static void Execute()
        {
            var projects = SqlSugarHelper.Db.Queryable<ec_projectEntity>().ToList();
                //项目过滤条件，可以配置备份的项目
                //.Where(x => x.ProjectId == "c151f5d4-cbe1-4522-945c-501b1ad990d5").ToList();
            projects.ForEach(x =>
            {
                //UserInfo userInfo = LoginUserInfo.Get();
                //获取要备份的数据库表名
                List<string> list_tblName = BackupTable.GetBackupTableList();
                list_tblName.Add("lr_base_annexesfile");
                string filename = x.ProjectName + "_备份_" + DateTime.Now.ToString("yyyyMMddHHmmss");//文件名
                string filePath = string.Format("{0}/{1}/{2}/{3}/{4}/{5}", Config.GetValue("AnnexesFile"), "Backup", "System", DateTime.Now.ToString("yyyyMMdd"), Guid.NewGuid().ToString("D"), filename);
                string ZipFilesPath = filePath + ".zip";//ZIP包存放的路径
                long fileSize = 0;
                var bakupIBLL = new ec_project_bakupBLL();
                new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        string sqlitePath = Path.Combine(filePath, "dbbackup");
                        if (!Directory.Exists(sqlitePath))
                        {
                            Directory.CreateDirectory(sqlitePath);
                        }

                        sqlitePath = Path.Combine(sqlitePath, "sqlitebackup.db");
                        //创建sqlite文件
                        SqliteHelper.NewSqliteDatabase(sqlitePath);
                        string fileBackupPath = filePath + "/filebackup";
                        if (!Directory.Exists(fileBackupPath))
                        {
                            Directory.CreateDirectory(fileBackupPath);
                        }
                        //往sqlite里面添加和插入表数据
                        bakupIBLL.CreateAndAddBySqlit(x.ProjectId, list_tblName, sqlitePath, fileBackupPath, x.ProjectIndex.ToString());
                        //提交
                        SqliteHelper.SaveChange();

                        //将集合生成为压缩文件
                        ZipOutputStream stream = new ZipOutputStream(File.Create(ZipFilesPath));
                        stream.SetLevel(0); // 压缩级别 0-9
                        byte[] buffer = new byte[4096]; //缓冲区大小
                        string[] filenames = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);
                        foreach (string file in filenames)
                        {
                            ZipEntry entry = new ZipEntry(file.Replace(filePath, ""));
                            stream.PutNextEntry(entry);

                            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                int sourceBytes;
                                do
                                {
                                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                    stream.Write(buffer, 0, sourceBytes);
                                } while (sourceBytes > 0);
                            }
                        }
                        fileSize = stream.Length;

                        stream.Finish();
                        stream.Close();
                        //Directory.Delete(filePath.Replace('/', '\\'), true);
                    }
                    catch (Exception ex)
                    {
                        SqliteHelper.Close();
                    }
                }).ContinueWith(t => {
                    //往数据库备份表中和附件表中插入数据
                    bakupIBLL.SaveEntity(x.ProjectId, x.ProjectName, ZipFilesPath, "System", "超级管理员", fileSize);
                });
            });
        }
    }
}
